<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-btn="filterInfo.btnList"
        >
          <template v-slot:filter-btnDelete>
            <el-button
              @click="del()"
              v-if="$permission('purchSubscribeTemplate:del')"
              :disabled="!tableInfo.selections.length"
              >删除</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-name="scope">
          <span
            class="slip-edit"
            v-if="$permission('purchSubscribeTemplate:details')"
            @click="showDetail(scope.row)"
            >{{ scope.row.name }}</span
          >
          <span v-else>{{ scope.row.name || '-' }}</span>
        </template>
      </TableContainer>
    </div>

    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />

    <!-- 新增或修改 -->
    <PurchTemplateModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :purchTemplateId="modifyInfo.purchTemplateId"
      @returnModify="returnModify"
    />
    <PurchTemplateDetail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />

    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
  </div>
</template>

<script setup name="purchSubscribeTemplate">
import {
  deletePurchTemplate,
  getPurchTemplateCustomizeListPage,
} from '@/api/purch.js'
import PurchTemplateModify from './modify'
import PurchTemplateDetail from './detail'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      templateType: {
        asTbName: 'purch_template',
        asName: 'template_type',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        queryResource: 0,
        value: 1,
      },
      deptAuth: {
        asTbName: 'purch_template',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
    // sort: "create_time desc",
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('purchSubscribeTemplate:add'),
      event: create,
    },
    { type: 'slot', value: 'btnDelete', event: del, label: '删除' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('purchSubscribeTemplate:update'),
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: del,
        show: proxy.$permission('purchSubscribeTemplate:del'),
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  exportId: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.value.purchTemplateId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      fieldName: 'templateType',
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 1,
    },
    {
      fieldName: 'deptId',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 初始化验证
function initRules() {
  formInfo.value.rules = proxy.$initRules(formInfo.value.fieldList)
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//新增
function create() {
  modifyInfo.value.title = '新增申购模板'
  modifyInfo.value.purchTemplateId = ''
  modifyInfo.value.visible = true
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.value.title = '修改申购模板'
  modifyInfo.value.purchTemplateId = data.id
  modifyInfo.value.visible = true
}
function del(row) {
  if (row && row.id) {
    remove([row.id])
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = tableInfo.value.selections.map((row) => row.id)
        remove(ids)
      })
  }
}
function remove(ids) {
  console.log(ids)
  deletePurchTemplate(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
  depotId.value = ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      console.log(tableInfo.value.selections)
      break
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: 'purchSubTemplate-com.slip.spd.entity.vo.purch.PurchTemplateVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getPurchTemplateCustomizeListPage
      getList()
    }
  })
}

let obj = ref({
  name: {
    label: '模板名称',
    value: 'name',
    type: 'slot',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    componentType: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchSubscribeTemplate:price'),
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
getCustomize()
</script>

<style scoped></style>
